#include <iostream>
#include <string>
#include <assert.h>
#include <cstdio>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
using namespace std;

int main()
{
    //创建管道
    int pipefd[2] = {0};
    int ret = pipe(pipefd);
    assert(ret == 0);
    (void)ret;
    //创建子进程

    pid_t id = fork();
    if(id == 0)
    {
        //子进程
        close(pipefd[1]);
        char buffer[1024];
        while(true)
        {
            ssize_t sz = read(pipefd[0], buffer, sizeof(buffer)-1);
            if(sz > 0)
            {
                buffer[sz] = 0;
                cout << "father#" << buffer << endl;
            }        
        }
        exit(0);
    }
    //父进程

    close(pipefd[0]);
    string str = "我是父进程，我正在和你通讯";
    int count = 0;
    char buffer_end[1024];

    while(true)
    {
        snprintf(buffer_end, sizeof(buffer_end), "%s[%d]", str.c_str(), count);
        count++;
        size_t len = strlen(buffer_end);
        //cout << len << endl;
        write(pipefd[1], buffer_end, len);
        sleep(1);
    }
    close(pipefd[1]);
    pid_t pid = waitpid(id, nullptr, 0);
    assert(pid != -1);
    (void)pid;
    //关闭对应的fd
    //子进程读数据父进程写数据
    //关闭文件，父进程等待子进程退出

    return 0;
}